import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Json解析',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        splashColor: Colors.transparent,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Json解析'),
        ),
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  String content = "";

  @override
  void initState() {
    super.initState();
    getAuthors().then((value) {
      content = value.toString();
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: Text(
          content,
          style: TextStyle(fontSize: 14),
        ),
      ),
    );
  }
}

class Author {
  String nickName;
  String roomName;

  Author({this.nickName, this.roomName});

  Author.withMap(Map<String, dynamic> parsedMap) {
    this.nickName = parsedMap['nickName'];
    this.roomName = parsedMap['roomName'];
  }

  @override
  String toString() {
    return 'Author{nickName: $nickName, roomName: $roomName}';
  }
}

Future<List<Author>> getAuthors() async {
  // 去取json文件
  String jsonStr = await rootBundle.loadString("assets/author.json");

  // 转换为List或者Map类型
  final jsonResult = json.decode(jsonStr);

  // 遍历jsonResult
  List<Author> authorList = List();
  for (Map<String, dynamic> map in jsonResult) {
    authorList.add(Author.withMap(map));
  }
  return authorList;
}
